<template>
  <div class="progress-update-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="header-content">
          <span>项目进度管理</span>
          <div class="header-right">
          <!-- 修正 el-select 组件 -->
          <el-select
              v-model="selectedProject"
              filterable
              allow-create
              @change="handleProjectChange"
              style="margin-right: 20px; width: 200px;"
              placeholder="选择或输入项目"
          >
            <!-- 确保 value 绑定为字符串 -->
            <el-option
                v-for="project in projectList"
                :key="project.id"
                :label="project.projectName"
                :value="project.projectName"
            ></el-option>
          </el-select>
          <el-progress
              :percentage="progressPercentage"
              :stroke-width="18"
              status="success"
              style="width: 300px;"
          ></el-progress>
          </div>
        </div>
      </div>

      <!-- 任务管理 -->
      <div class="section">
        <h3>任务管理</h3>
        <!-- 队长显示任务添加表单 -->
        <div v-if="userRole === 1">
          <el-form :model="form" ref="form">
            <el-input
                v-model="form.newTask"
                placeholder="请输入新任务"
                style="width: 400px; margin-right: 10px"
            ></el-input>
            <el-button
                type="primary"
                @click="addNewTask"
            >
              添加任务
            </el-button>
          </el-form>
          <el-select
              v-model="selectedMembers"
              multiple
              filterable
              placeholder="选择负责队员"
              class="member-select"
          >
            <el-option
                v-for="member in teamMembers"
                :key="member.id"
                :label="member.userName"
                :value="member.userName"
            ></el-option>
          </el-select>
        </div>
        <!-- 任务列表 -->
        <el-table
            :data="currentProjectData.tasks"
            style="margin-top: 20px"
            empty-text="暂无任务">
          <el-table-column width="50">
            <template slot-scope="scope">
              <el-checkbox
                  v-model="scope.row.completed"
                  @change="updateTaskStatus(scope.row)"
                  :disabled="userRole === 3"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="task" label="任务内容">
            <template slot-scope="scope">
              <span :class="{ 'completed-task': scope.row.task }">
                {{ scope.row.task }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="responsibleName" label="负责人" width="180"></el-table-column>
          <el-table-column prop="createTime" label="最后更新时间" width="180"></el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click="removeTask(scope.row.id)"
                  :disabled="userRole === 3"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="section">
        <h3>下一步计划</h3>
        <!-- 队长显示计划添加表单 -->
        <div v-if="userRole === 1">
          <el-form :model="form">
            <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入下一步计划"
                v-model="form.newNextStep"
            ></el-input>
            <el-button
                type="primary"
                @click="addNextStep"
                style="margin-top: 10px"
            >
              添加计划
            </el-button>
          </el-form>
        </div>
        <el-table :data="currentProjectData.nextSteps" style="margin-top: 20px">
          <el-table-column prop="createTime" label="时间" width="180"></el-table-column>
          <el-table-column prop="plan" label="计划内容"></el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click="removeTask2(scope.row.id)"
                  :disabled="userRole === 3"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 遇到的问题 -->
      <div class="section">
        <h3>遇到的问题</h3>
        <!-- 非老师显示问题添加表单 -->
        <div v-if="userRole !== 3">
          <el-form :model="form">
            <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入遇到的问题"
                v-model="form.newIssue"
            ></el-input>
            <el-button
                type="primary"
                @click="addIssue"
                style="margin-top: 10px"
            >
              添加问题
            </el-button>
          </el-form>
        </div>
        <el-collapse style="margin-top: 20px">
          <el-collapse-item
              v-for="(issue, index) in currentProjectData.issues"
              :key="index"
              :title="issue.problem"
          >
            <div>记录时间：{{ issue.createTime }}</div>
            <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeTask3(issue.id)"
                :disabled="userRole === 3"
            ></el-button>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 假设从Vuex或API获取用户角色
      teamMembers:[],
      userRole: '', // 可选值：'captain', 'member', 'teacher'
      selectedProject: '', // 改为字符串类型，存储当前选中的项目名
      currentProjectData: { // 替换原来的 projects 对象，存储当前项目数据
        tasks: [],
        nextSteps: [],
        issues: []
      },
      selectedMembers:'',
      projectList: [],       // 从后端获取的项目列表
      form: {
        newTask: '',
        newNextStep: '',
        newIssue: ''
      }
    };
  },
  computed: {
    progressPercentage() {
      const tasks = this.currentProjectData.tasks;
      if (tasks.length === 0) return 0;
      const completed = tasks.filter(t => t.completed).length;
      return Math.round((completed / tasks.length) * 100);
    }
  },
  created() {
    this.fetchProjects();

  },
  methods: {
    async load() {
      try {
        const res = await this.$request.get(`/project/selectprojectstudent?projectName=${encodeURIComponent(this.selectedProject)}`);
        this.teamMembers = res.data;
      } catch (error) {
        this.$message.error('获取队员数据失败');
      }
    },
    // 获取项目列表
    async fetchProjects() {
      try {
        const res = await this.$request.get('/project/selectUserProject');
        this.projectList = res.data;

        if (this.projectList.length === 0) {
          await this.createDefaultProject();
        } else {

          this.selectedProject = this.projectList[0].projectName;
          await this.fetchProjectData(this.selectedProject);
        }
      } catch (error) {
        this.$message.error('获取项目列表失败');
        // 网络异常时尝试加载本地默认项目
        if (this.projectList.length === 0) {
          this.loadLocalDefaultProject();
        }
      }
    },

    // 新增方法：创建默认项目
    async createDefaultProject() {
      try {
        const res = await this.$request.post('/api/projects', {
          name: '默认项目',
          tasks: [],
          nextSteps: [],
          issues: []
        });

        this.projectList.push(res.data.name);
        this.selectedProject = res.data.name;
        this.currentProjectData = res.data;
      } catch (error) {
        this.$message.error('创建默认项目失败');
        this.loadLocalDefaultProject();
      }
    },

    // 新增方法：加载本地默认项目（当后端不可用时）
    loadLocalDefaultProject() {
      this.projectList = ['默认项目'];
      this.selectedProject = '默认项目';
      this.currentProjectData = {
        tasks: [{
          id: Date.now(),
          content: "示例任务",
          completed: false,
          time: new Date().toLocaleString()
        }],
        nextSteps: [],
        issues: []
      };
    },


    // 获取项目详情
    async fetchProjectData(projectName) {
      try {
        await this.loudsss(this.selectedProject);
        const res = await this.$request.get(`/project/selectCurrentProjectData?projectName=${encodeURIComponent(this.selectedProject)}`);
        this.currentProjectData = res.data;
        const ress = await this.$request.get(`/project/selectprojectstudent?projectName=${encodeURIComponent(this.selectedProject)}`);
        this.teamMembers = ress.data;

      } catch (error) {
        this.$message.error('获取项目数据失败');
      }
    },

    // 项目切换处理
    async handleProjectChange(val) {
      await this.loudsss(val);
      await this.fetchProjectData(val);


    },
    async loudsss(val) {
      try {
        const res = await this.$request.get(`/project/qx?projectName=${encodeURIComponent(val)}`);
        this.userRole = res.data[0].privilege;
      } catch (error) {
        this.$message.error('获取权限数据失败');
      }
    },
    // 添加新任务
    async addNewTask() {
      if (!this.form.newTask.trim()) return;

      try {
        const res = await this.$request.post(`/project/addTask?selectedMembers=${encodeURIComponent(this.selectedMembers)}`,{
          project: this.selectedProject,
          content: this.form.newTask});


        // 2. 添加成功处理
        this.$message.success('任务添加成功！');
this.selectedMembers='';
        // 3. 清空输入框
        this.form.newTask = '';

        // 4. 刷新当前项目数据
        await this.fetchProjectData(this.selectedProject);
      } catch (error) {
        this.$message.error('添加任务失败');
      }
    },

    // 更新任务状态
    async updateTaskStatus(task) {
      try {
        await this.$request.post(`/project/updateTaskStatus?id=${encodeURIComponent(task.id)}`, {
          completed: task.completed
        });
        task.createTime = new Date().toLocaleString();
      } catch (error) {
        this.$message.error('更新任务状态失败');
      }
    },

    // 删除任务
    async removeTask(id) {

      try {
        await this.$request.post(`/project/removeTask?id=${encodeURIComponent(id)}`);
        this.$message.success('任务删除成功！');
        // 4. 刷新当前项目数据
        await this.fetchProjectData(this.selectedProject);
      } catch (error) {
        this.$message.error('删除失败');
      }
    },
    // 删除计划
    async removeTask2(id) {

      try {
        await this.$request.post(`/project/removePlan?id=${encodeURIComponent(id)}`);
        this.$message.success('计划删除成功！');
        // 4. 刷新当前项目数据
        await this.fetchProjectData(this.selectedProject);
      } catch (error) {
        this.$message.error('删除失败');
      }
    },
    // 删除问题
    async removeTask3(id) {

      try {
        await this.$request.post(`/project/removeProblem?id=${encodeURIComponent(id)}`);
        this.$message.success('问题删除成功！');
        // 4. 刷新当前项目数据
        await this.fetchProjectData(this.selectedProject);
      } catch (error) {
        this.$message.error('删除失败');
      }
    },

    // 添加下一步计划
    async addNextStep() {
      if (!this.form.newNextStep.trim()) return;

      try {
        const res = await this.$request.post('/project/addPlan', {
          project: this.selectedProject,
          content: this.form.newNextStep
        });

        // 2. 添加成功处理
        this.$message.success('计划添加成功！');

        // 3. 清空输入框
        this.form.newNextStep = '';

        // 4. 刷新当前项目数据
        await this.fetchProjectData(this.selectedProject);
      } catch (error) {
        this.$message.error('添加计划失败');
      }
    },

    // 添加问题
    async addIssue() {
      if (!this.form.newIssue.trim()) return;

      try {
        const res = await this.$request.post('/project/addProblem', {
          project: this.selectedProject,
          content: this.form.newIssue
        });
        // 2. 添加成功处理
        this.$message.success('任务添加成功！');

        // 3. 清空输入框
        this.form.newIssue = '';

        // 4. 刷新当前项目数据
        await this.fetchProjectData(this.selectedProject);
      } catch (error) {
        this.$message.error('添加问题失败');
      }
    },

    getCurrentTime() {
      return new Date().toLocaleString();
    }
  }
};
</script>
<style scoped>
.completed-task {
  text-decoration: line-through;
  color: #909399;
}
.task-form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-row {
  display: flex;
  gap: 10px;
  align-items: center;
}

.task-input {
  flex: 1;
  max-width: 400px;
}

.member-select {
  width: 250px;
}

.add-button {
  align-self: flex-start;
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    align-items: stretch;
  }

  .task-input,
  .member-select {
    max-width: none;
    width: 100%;
  }
}
.progress-update-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.section {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

h3 {
  color: #409EFF;
  margin-bottom: 15px;
}

.el-table::before {
  height: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-right {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>